//
//  PhotoPickerViewController.swift
//  XMGWB
//
//  Created by apple on 15/12/11.
//  Copyright © 2015年 xiaomage. All rights reserved.
//

import UIKit

class PhotoPickerViewController: UICollectionViewController {
    
    // 存放所有照片的数组
    var images : [UIImage] = [UIImage]()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return images.count + 1
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 1.创建cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! PhotoPickerCell
        cell.delegate = self
        
        // 2.给cell设置数据
        cell.image = indexPath.item >= images.count ? nil : images[indexPath.item]
        
        // 3.返回cell
        return cell
    }
}

extension PhotoPickerViewController : PhotoPickerCellDelegate{
    func photoPickerCellAddBtnClick(cell: PhotoPickerCell) {
        // 1.判断数据源是否可用
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            print("图片库不可用")
            return
        }
        
        // 2.创建照片选择控制器
        let ipc = UIImagePickerController()
        
        // 3.设置照片源
        ipc.sourceType = .PhotoLibrary
        
        // 4.设置代理
        ipc.delegate = self
        
        // 5.弹出控制器
        self.presentViewController(ipc, animated: true, completion: nil)
    }
    
    func photoPickerCellremoveBtnClick(cell: PhotoPickerCell) {
        let indexPath = collectionView?.indexPathForCell(cell)!
        
        // 移除图片
        images.removeAtIndex(indexPath!.item)
        
        // 刷新表格
        collectionView?.reloadData()
    }
}

extension PhotoPickerViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        // 获取照片
        var image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        // 压缩图片
        image = scaleImage(image, width: 300)
        
        // 将照片放入数组中
        images.append(image)
        
        // 退出控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
        
        // 刷新表格
        collectionView?.reloadData()
    }
    
    func scaleImage(image : UIImage, width : CGFloat) -> UIImage {
        // 0.计算Size
        let height = width * image.size.height / image.size.width
        let size = CGSize(width: width, height: height)
        
        // 1.获取图片上下文
        UIGraphicsBeginImageContext(size)
        
        // 2.将图片画在上下文中,并且保持宽高比
        image.drawInRect(CGRect(origin: CGPointZero, size: size))
        
        // 3.从上下文中获取最新的图片
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        
        // 4.关闭图形上下文
        UIGraphicsEndImageContext()
        
        // 5.返回图片
        return newImage
    }
}

@objc
protocol PhotoPickerCellDelegate : NSObjectProtocol {
    optional func photoPickerCellAddBtnClick(cell : PhotoPickerCell)
    optional func photoPickerCellremoveBtnClick(cell : PhotoPickerCell)
}

class PhotoPickerCell : UICollectionViewCell {
    
    // 代理属性
    var delegate : PhotoPickerCellDelegate?
    
    // 添加照片的按钮
    @IBOutlet weak var addBtn: UIButton!
    
    // 删除按钮
    @IBOutlet weak var removeBtn: UIButton!
    
    // 添加图片的属性
    var image : UIImage? {
        didSet {
            if image == nil {
                addBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
                addBtn.setBackgroundImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
                addBtn.userInteractionEnabled = true
                removeBtn.hidden = true
            } else {
                addBtn.setBackgroundImage(image, forState: UIControlState.Normal)
                addBtn.userInteractionEnabled = false
                removeBtn.hidden = false
            }
        }
    }
    
    @IBAction func addBtnClick() {
        if let tempDelegate = delegate {
            if tempDelegate.respondsToSelector("photoPickerCellAddBtnClick:") {
                tempDelegate.photoPickerCellAddBtnClick!(self)
            }
        }
    }
    
    @IBAction func removeBtnClick() {
        if let tempDelegate = delegate {
            if tempDelegate.respondsToSelector("photoPickerCellremoveBtnClick:") {
                tempDelegate.photoPickerCellremoveBtnClick!(self)
            }
        }
    }
}

class PhotoPickerCollectionViewLayout : UICollectionViewFlowLayout {
    override func prepareLayout() {
        super.prepareLayout()
        
        // 0.定义常量
        let margin : CGFloat = 20
        let col : CGFloat = 3
        
        // 1.计算cell的宽度
        let width = (collectionView!.bounds.size.width - (col + 1) * margin) / col
        
        // 2.设置item的size
        itemSize = CGSize(width: width, height: width)
        
        // 3.设置间距
        minimumInteritemSpacing = margin
        minimumLineSpacing = margin
        
        // 4.设置collectionView的内边距
        sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
    }
}